package vivek.project.pocketmoney.common
{
	import flash.data.*;
	import flash.desktop.NativeApplication;
	import flash.errors.SQLError;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	import mx.controls.Alert;
	import mx.formatters.CurrencyFormatter;
	import mx.formatters.DateFormatter;
	import mx.resources.ResourceManager;
	import mx.utils.StringUtil;
	
	import vivek.project.pocketmoney.*;
	import vivek.project.pocketmoney.admin.model.AdminDataCache;
	import vivek.project.pocketmoney.admin.model.AdminDataModel;
	import vivek.project.pocketmoney.common.logger.LogCache;
	import vivek.project.pocketmoney.common.utils.CommonUtils;
	import vivek.project.pocketmoney.expenses.SummaryScript;
	import vivek.project.pocketmoney.expenses.model.ExpenseDataModel;
	import vivek.project.pocketmoney.expenses.scripts.ExpenseRecurssions;
	import vivek.project.pocketmoney.expenses.scripts.ExpenseSQLScript;
	import vivek.project.pocketmoney.investments.model.FixedIncomeDataModel;
	import vivek.project.pocketmoney.investments.model.PropertyDataModel;
	import vivek.project.pocketmoney.loans.LoanModel;
	import vivek.project.pocketmoney.mutualfund.model.MutualFundModel;
	import vivek.project.pocketmoney.stocks.model.StockDataModel;

	public class PocketMoneyInit
	{
		public static var currencyFormatter:CurrencyFormatter=new CurrencyFormatter();
		public static var dateFormatter:DateFormatter=new DateFormatter();
		public static var timeFormatter:DateFormatter=new DateFormatter();
		public function PocketMoneyInit()
		{
			initApp();
			var er:ExpenseRecurssions=new ExpenseRecurssions();
		}
		public var currentVersion:String="5.4";
		public var file:File;
		private var _statement:SQLStatement=new SQLStatement();
		private var availableVersions:Array=new Array();
		public function init():void
		{
			file=File.applicationStorageDirectory;
			file=file.resolvePath("Preferences/version.txt");
			availableVersions=loadFile("vivek/project/pocketmoney/common/upgrade/versions.txt", '\n');
			trace(file.nativePath);
			if (file.exists)
			{
				checkVersion();
			}
			else
			{
				firstRun();
			}
		}
		private function checkVersion():void
		{
			var stream:FileStream=new FileStream();
			var prevVersion:String=currentVersion;
			try
			{
				stream.open(file, FileMode.READ);
				prevVersion=stream.readUTFBytes(stream.bytesAvailable);
				stream.close();
			}
			catch (error:Error)
			{
			}
			var pv:Number=Number(prevVersion);
			var cv:Number=Number(currentVersion);
			var versionToUpgrade:Array=new Array();
			for each (var version:Object in availableVersions)
			{
				if (version > cv)
					versionToUpgrade.push(version);
			}
			if (pv < cv)
			{
				var i:int=updateDataBase();
				if (i == 0)
				{
					saveFile();
					Alert.show("You have been successfully upgraded to version " + currentVersion + ".\n");
				}
				else
					Alert.show("The database could not be upgraded to the next version, Some features might not function as intended");
			}
			else
			{
				//	Alert.show("You have the latest version of the application");
				//saveFile();
			}
		}
		private function firstRun():void
		{
			var cds:CreateDatabaseSQLScript=new CreateDatabaseSQLScript();
			checkVersion();
			saveFile();
		}
		private function initApp():void
		{
			init();
			runUpdater();
			var es:ExpenseSQLScript=new ExpenseSQLScript();
			var ss:SummaryScript=new SummaryScript();
			var am:AdminDataModel=AdminDataModel.getInstance();
			var edm:ExpenseDataModel=ExpenseDataModel.getInstance();
			var stockModel:StockDataModel=StockDataModel.getInstance();
			var investmentModel:FixedIncomeDataModel=FixedIncomeDataModel.getInstance();
			var mutualFundModel:MutualFundModel=MutualFundModel.getInstance();
			var propertyModel:PropertyDataModel=PropertyDataModel.getInstance();
			var loanModel:LoanModel=LoanModel.getInstance();
			var resourceManager:ResourceManager=new ResourceManager();
			var logCache:LogCache=new LogCache();
			//_sqlConnection.commit();	
			//	AdminDataCache.controlData.source=CommonUtils.loadFileFromStorage("controldata.txt", ",");
			dateFormatter.formatString=ResourceManager.getInstance().getString("FormattingValues", "DATE_FORMAT");
			timeFormatter.formatString=ResourceManager.getInstance().getString('FormattingValues', 'TIME_FORMAT');
			currencyFormatter.precision=ResourceManager.getInstance().getString('FormattingValues', 'CURRENCY_PRECISION');
			currencyFormatter.currencySymbol=ResourceManager.getInstance().getString('FormattingValues', 'CURRENCY_SYMBOL');
			currencyFormatter.thousandsSeparatorTo=ResourceManager.getInstance().getString('FormattingValues', 'THOUSANDS_SEPARATOR');
			currencyFormatter.decimalSeparatorTo=ResourceManager.getInstance().getString('FormattingValues', 'DECIMAL_SEPARATOR');
		}
		private function loadFile(file:String, delimiter:String):Array
		{
			var arrayList:Array=new Array();
			var sqlFile:File=File.applicationDirectory.resolvePath(file);
			var _sqlConnection:SQLConnection;
			if (sqlFile.exists)
			{
				var fileStream:FileStream=new FileStream();
				fileStream.open(sqlFile, FileMode.READ);
				var fileInfo:String=fileStream.readUTFBytes(fileStream.bytesAvailable);
				fileStream.close();
				var parts:Array=fileInfo.split(delimiter);
				for (var i:int; i < parts.length; i++)
				{
					arrayList.push(parts[i]);
				}
					//_sqlConnection.commit();	
			}
			return arrayList;
		}
		private function runUpdater():void
		{
			var appXml:XML=NativeApplication.nativeApplication.applicationDescriptor;
			var ns:Namespace=appXml.namespace();
			var appId:int=appXml.ns::id[0];
			var appVersion:int=appXml.ns::version;
			var appName:String=appXml.ns::filename[0];
			trace("appId:" + appId);
			trace("version:" + appVersion);
			trace("filename:" + appName);
			//var updater:Updater = new Updater();
		}
		private function saveFile():void
		{
			var stream:FileStream=new FileStream();
			stream.open(file, FileMode.WRITE);
			stream.writeUTFBytes(currentVersion);
			stream.close();
		}
		private function updateDataBase():int
		{
			var sqlFile:File=File.applicationDirectory.resolvePath("vivek/project/pocketmoney/common/upgrade/upgrade_" + currentVersion + ".sql");
			var _sqlConnection:SQLConnection;
			if (sqlFile.exists)
			{
				_sqlConnection=CommonData.getConnection();
				var _statement:SQLStatement=new SQLStatement();
				var fileStream:FileStream=new FileStream();
				fileStream.open(sqlFile, FileMode.READ);
				var fileInfo:String=fileStream.readUTFBytes(fileStream.bytesAvailable);
				fileStream.close();
				var parts:Array=fileInfo.split('\n');
				_sqlConnection.begin();
				_statement.sqlConnection=_sqlConnection;
				for (var i:int; i < parts.length; i++)
				{
					try
					{
						if ('' != parts[i])
						{
							_statement.text=parts[i];
							_statement.execute();
						}
					}
					catch (error:SQLError)
					{
						if (error.errorID != 3115)
						{
							_sqlConnection.rollback();
							_sqlConnection.close();
							return 9999;
						}
					}
				}
				_sqlConnection.commit();
			}
			return 0;
		}
	}
}